package com.demo.apparel.service.web.Impl;

import com.demo.apparel.dto.web.AdminLoginDTO;
import com.demo.apparel.dto.web.AdminLoginResponseDTO;
import com.demo.apparel.entity.Admin;
import com.demo.apparel.entity.AdminInfo;
import com.demo.apparel.exception.ServiceException;
import com.demo.apparel.mapper.web.AdminInfoMapper;
import com.demo.apparel.mapper.web.AdminMapper;
import com.demo.apparel.service.web.AdminService;
import com.demo.apparel.service.web.WechatApiService;
import com.demo.apparel.utils.JwtUtils;
import com.demo.apparel.vo.web.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AdminInfoMapper adminInfoMapper;

    @Autowired
    private WechatApiService wechatApiService;

    /**
     *
     * @param dto
     * @return
     */

    @Override
    public AdminLoginResponseDTO login(AdminLoginDTO dto) {
        String account = dto.getAccount();
        String password = dto.getPassword();

        Admin admin = adminMapper.selectByPhones(account);

        if (admin == null) {
            AdminInfo info = adminInfoMapper.selectByNickname(account);
            if (info != null) {
                admin = adminMapper.selectByIds(info.getAdminId());
            }
        }

        if (admin == null || !password.equals(admin.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }

        String token = jwtUtils.createToken(admin.getId(), null);

        AdminLoginResponseDTO response = new AdminLoginResponseDTO();
        response.setToken(token);
        response.setId(admin.getId());
        response.setIsSuper(admin.getIsSuper());
        return response;
    }




    /**
     *
     * @param adminId 管理员ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @Override
    public void updatePassword(String adminId, String oldPassword, String newPassword) {
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new ServiceException("400", "管理员不存在");
        }
        if (!oldPassword.equals(admin.getPassword())) {
            throw new ServiceException("400", "旧密码错误"); // 抛出统一异常
        }

        admin.setPassword(newPassword);
        adminMapper.updatePassword(admin); // 需要实现mapper对应方法
    }

    @Override
    public List<AdminVO> getAllAdminWithInfo() {
        List<Admin> admins = adminMapper.getAllAdmins();
        List<AdminVO> result = new ArrayList<>();

        for (Admin admin : admins) {
            AdminInfo info = adminInfoMapper.getInfoByAdminId(admin.getId());

            AdminVO vo = new AdminVO();
            vo.setId(admin.getId());
            vo.setPhone(admin.getPhone());
            vo.setIsSuper(admin.getIsSuper());
            vo.setCreatedTime(admin.getCreatedTime());

            if (info != null) {
                vo.setNickname(info.getNickname());
                vo.setAvatar(info.getAvatar());
                vo.setEmail(info.getEmail());
                vo.setGender(info.getGender());
            }

            result.add(vo);
        }

        return result;
    }


    @Override
    @Transactional
    public void addAdmin(Admin admin, AdminInfo adminInfo) {
        // 设置 ID 和时间
        String adminId = UUID.randomUUID().toString().replace("-", "");
        admin.setId(adminId);
        admin.setCreatedTime(LocalDateTime.now());
        admin.setUpdatedTime(LocalDateTime.now());

        // 默认密码，如果没传密码就设置成123456（这里你可以按需修改）
        if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
            admin.setPassword("123456");
        }

        adminMapper.insert(admin);

        // adminInfo 没传或传了空，自动填充默认值
        if (adminInfo == null) {
            adminInfo = new AdminInfo();
        }
        adminInfo.setId(UUID.randomUUID().toString().replace("-", ""));
        adminInfo.setAdminId(adminId);

        if (adminInfo.getNickname() == null) adminInfo.setNickname("");
        if (adminInfo.getAvatar() == null) adminInfo.setAvatar("https://tse3.mm.bing.net/th/id/OIP.Z9IvBYaIjiPNqSoTGzVsHwHaHa?rs=1&pid=ImgDetMain&o=7&rm=3");
        if (adminInfo.getEmail() == null) adminInfo.setEmail("");
        if (adminInfo.getGender() == null) adminInfo.setGender("");

        adminInfo.setCreatedTime(LocalDateTime.now());
        adminInfo.setUpdatedTime(LocalDateTime.now());

        adminInfoMapper.insert(adminInfo);
    }


    @Override
    public void deleteAdmin(String adminId) {
        // 先删除 admin_info 表记录
        adminInfoMapper.deleteByAdminId(adminId);

        // 再删除 admin 表记录
        adminMapper.deleteById(adminId);
    }

    @Override
    public AdminLoginResponseDTO wxLogin(String code) {
        // 1. 调用微信接口获取 openid
        String openid = wechatApiService.getOpenidByCode(code); // 你可以用 RestTemplate 或 WebClient
        if (openid == null) {
            throw new RuntimeException("微信登录失败，获取 openid 失败");
        }

        // 2. 根据 openid 查询管理员
        Admin admin = adminMapper.selectByOpenid(openid);
        if (admin == null) {
            throw new RuntimeException("该微信未绑定后台管理员，请先绑定账号");
        }

        // 3. 生成 token
        String token = jwtUtils.createToken(admin.getId(), null);

        // 4. 返回登录信息
        AdminLoginResponseDTO response = new AdminLoginResponseDTO();
        response.setToken(token);
        response.setId(admin.getId());
        response.setIsSuper(admin.getIsSuper());
        return response;
    }

    @Override
    public void bindWx(String adminId, String code) {
        // 1. 调用微信接口获取 openid
        String openid = wechatApiService.getOpenidByCode(code);
        if (openid == null) {
            throw new RuntimeException("微信绑定失败，获取 openid 失败");
        }

        // 2. 检查 openid 是否被其他管理员绑定
        Admin exists = adminMapper.selectByOpenid(openid);
        if (exists != null && !exists.getId().equals(adminId)) {
            throw new RuntimeException("该微信已绑定其他管理员账号");
        }

        // 3. 更新 admin 表 openid 字段
        adminMapper.updateOpenid(adminId, openid);
    }

}
